package com.gezi.admin.aop.log;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.gezi.admin.module.sys.log.SysOperateLogEntity;
import com.gezi.admin.module.sys.log.SysOperateLogService;
import com.gezi.admin.module.sys.log.model.SysOperateLogStateEnum;
import com.gezi.admin.module.sys.login.model.LoginLoginModel;
import com.gezi.admin.module.sys.user.SysUserEntity;
import com.gezi.admin.module.sys.user.SysUserService;
import com.gezi.admin.security.SecurityUtil;
import com.gezi.admin.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;

/**
 * 操作日志记录处理
 * @Author 格子软件
 * @createDate 2024/2/10 09:00
 * @contact 公众号：格子软件 微信：13716343106 邮箱：1424529270@qq.com
 */
@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Resource
    public SysUserService sysUserService;

    @Resource
    public SysOperateLogService sysOperateLogService;

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(logging)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Logging logging, Object jsonResult) {
        handleLog(joinPoint, logging, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(logging)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Logging logging, Exception e) {
        handleLog(joinPoint, logging, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Logging logging, final Exception e, Object requestResult) {
        try {

            // *========数据库日志=========*//
            SysOperateLogEntity sysOperateLogEntity = new SysOperateLogEntity();
            // 请求的地址
            String ip = RequestUtil.getClientIP();
            sysOperateLogEntity.setOperIp(ip);
            String requestUrl = RequestUtil.getRequest().getRequestURI();
            sysOperateLogEntity.setOperUrl(requestUrl);
            String userId = SecurityUtil.getUserId();
            if(requestUrl.contains("/sys/login/login")){
                LoginLoginModel loginLoginModel = (LoginLoginModel) joinPoint.getArgs()[0];
                SysUserEntity sysUserEntity = sysUserService.findByLoginName(loginLoginModel.getUsername());
                if(sysUserEntity != null){
                    userId = sysUserEntity.getId();
                }
            }
            sysOperateLogEntity.setUserId(userId);

            if (e == null) {
                sysOperateLogEntity.setState(SysOperateLogStateEnum.SUCCESS.name());
            }else{
                sysOperateLogEntity.setState(SysOperateLogStateEnum.FAIL.name());
                sysOperateLogEntity.setStateRemark(e.getMessage());
            }

            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            sysOperateLogEntity.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            sysOperateLogEntity.setRequestMethod(RequestUtil.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, logging, sysOperateLogEntity, requestResult);
            // 保存数据库
            sysOperateLogService.save(sysOperateLogEntity);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param logging    日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Logging logging, SysOperateLogEntity operLog, Object requestResult) throws Exception {
        // 设置action动作
        operLog.setBusinessType(logging.value());
        // 设置标题
        operLog.setTitle(logging.tags());
        // 设置客户端
        operLog.setClient(SecurityUtil.getClient());
        // 是否需要保存request，参数和值
        if (logging.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
        // 是否需要保存response，参数和值
        if (logging.isSaveResponseData() && ObjectUtil.isNotNull(requestResult)) {
            operLog.setRequestResult(JSON.toJSONString(requestResult));
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param sysOperateLogEntity 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperateLogEntity sysOperateLogEntity) throws Exception {
        String requestMethod = sysOperateLogEntity.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            sysOperateLogEntity.setRequestParam(params);
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) RequestUtil.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            sysOperateLogEntity.setRequestParam(paramsMap.toString());
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        params.append(JSON.toJSONString(o)).append(" ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
            || o instanceof BindingResult;
    }
}
